﻿using System;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace TypedROBIN.Imaging
{
    public class Thumbnail
    {
        public void Generate(string imageFile, string output, int outputWidth, int outputHeight)
        {
            Size size = new Size(outputWidth, outputHeight);
            FileStream fs = new FileStream(imageFile, FileMode.Open);
            System.Drawing.Image imgToResize = Bitmap.FromStream(fs, false, false);
            int sourceWidth = imgToResize.Width;
            int sourceHeight = imgToResize.Height;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)size.Width / (float)sourceWidth);
            nPercentH = ((float)size.Height / (float)sourceHeight);

            //if (nPercentH < nPercentW)
            if (nPercentH > nPercentW)
            {
                nPercent = nPercentH;
            }
            else
            {
                nPercent = nPercentW;
            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap b = new Bitmap(outputWidth, outputHeight);
            Graphics g = Graphics.FromImage((System.Drawing.Image)b);
            g.FillRectangle(Brushes.White, 0, 0, outputWidth, outputHeight);
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //int x = destWidth == imageSize ? 0 : Convert.ToInt32((imageSize - destWidth) / 2);
            //int y = destHeight == imageSize ? 0 : Convert.ToInt32((imageSize - destHeight) / 2);
            int x = 0;
            int y = 0;
            try
            {
                g.DrawImage(imgToResize, x, y, destWidth, destHeight);
                //b.Save(thumbnailPath, ImageFormat.Jpeg);
                ImageCodecInfo ici = new Utils().GetImageCodec(output);
                EncoderParameters ep = new EncoderParameters();
                ep.Param[0] = new EncoderParameter(Encoder.Quality, (long)72);
                b.Save(output, ici, ep);
            }
            catch (Exception ex)
            {
                Console.WriteLine("無法儲存轉檔的縮圖，訊息是: " + ex.Message, ex);
            }
            finally
            {
                g.Dispose();
                b.Dispose();
                fs.Dispose();
                imgToResize.Dispose();
                fs = null;
                g = null;
                b = null;
                imgToResize = null;
            }
        }
    }
}
